package it.tukano.swingdeco.text;

import it.tukano.fun.Function3;
import it.tukano.swingdeco.controls.JPopupMenuExt;
import java.awt.Component;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import javax.swing.AbstractButton;
import javax.swing.JMenuItem;
import javax.swing.text.JTextComponent;

/**
 * A default cut-copy-paste-select all-clear popup menu for text components
 * @author pgi
 */
public class DefaultTextPopupMenu extends JPopupMenuExt implements Function3<Component, Point, AbstractButton, Void> {

    /* Serial version of this class */
    private static final long serialVersionUID = 0;

    public static DefaultTextPopupMenu newInstance(final JTextComponent parent) {
        final DefaultTextPopupMenu menu = new DefaultTextPopupMenu();
        menu.addListener(menu);
        menu.bind(parent);
        menu.onPopupWillBecomeVisible(new Runnable() {

            public void run() {
                menu.cut.setEnabled(parent.isEditable() && parent.getSelectionEnd() != parent.getSelectionStart());
                menu.paste.setEnabled(parent.isEditable() && Toolkit.getDefaultToolkit().getSystemClipboard().isDataFlavorAvailable(DataFlavor.stringFlavor));
                menu.copy.setEnabled(parent.getSelectionEnd() != parent.getSelectionStart());
                menu.selectAll.setEnabled(parent.getDocument().getLength() != 0);
                menu.clear.setEnabled(parent.getDocument().getLength() != 0);
            }
        });
        return menu;
    }

    private final JMenuItem cut, copy, paste, selectAll, clear;

    /**
     * Instance initializer
     */
    protected DefaultTextPopupMenu() {
        appendMenuItem(selectAll = new JMenuItem("Select All"));
        appendMenuItem(clear = new JMenuItem("Clear"));
        appendMenuItem(cut = new JMenuItem("Cut"));
        appendMenuItem(copy = new JMenuItem("Copy"));
        appendMenuItem(paste = new JMenuItem("Paste"));
    }

    public Void apply(Component p1, Point p2, AbstractButton p3) {
        JTextComponent component = (JTextComponent) p1;
        if(p3 == cut) {
            component.cut();
        } else if(p3 == copy) {
            component.copy();
        } else if(p3 == paste) {
            component.paste();
        } else if(p3 == selectAll) {
            component.selectAll();
        } else if(p3 == clear) {
            component.setText("");
        }
        return null;
    }

    @Override
    public JPopupMenuExt bind(Component component) {
        if (!(component instanceof JTextComponent)) {
            throw new IllegalArgumentException("component must be a textcomponent");
        }
        return super.bind(component);
    }
}
